let {chromium} = require("playwright");
var path = require("path");
/**
 * 
 * @param {string} mapStr 
 */
function map (mapStr){
    let mapObj = {};
    mapStr.split(',').forEach(key=>{
        mapObj[key] = true;
    });
    return (str)=>mapObj[str];
}
playwright.selectors
const formatMap = map('A0,A1,A2,A3,A4,A5,A6');

/**
 * 
 * @param {array} avgsArray 
 * @returns 
 */

function handlerArgs(avgsArray){
    avgsArray = avgsArray.slice(2);
    let avgsObj = {};
    let crossAvgInd = avgsArray.indexOf('-c');
    if(crossAvgInd != -1){
        avgsObj.c = true;
        avgsArray.splice(crossAvgInd,1);
    }else{
        avgsObj.c = false;
    }

    let formatAvgInd = avgsArray.indexOf('-f');
    if(formatAvgInd != -1){
        var format = avgsArray[formatAvgInd+1]?avgsArray[formatAvgInd+1].toUpperCase():'';
        if(!formatMap(format)){
            return false;
        }
        avgsObj.f = format;
        avgsArray.splice(formatAvgInd,2);
    }else{
        avgsObj.f = 'A4';
    }

    if(avgsArray.length != 4 || !avgsArray.length){
        return false;
    }

    let iAvgInd = avgsArray.indexOf('-i');
    let oAvgInd = avgsArray.indexOf('-o');
    if(!~iAvgInd || !~oAvgInd || Math.abs(iAvgInd - oAvgInd) != 2 || (iAvgInd != 0 && oAvgInd != 0)){
        return false
    }
    avgsObj.i = avgsArray[iAvgInd+1];
    avgsObj.o = avgsArray[oAvgInd+1];
    return avgsObj;
}

let avgs = handlerArgs(process.argv);

if(!avgs){
    console.log("参数异常!");
    return;
}

(async ()=>{
    try{
        var browser = await chromium.launch();
        const context = await browser.newContext();
        const page = await context.newPage();
        await page.goto(path.normalize(avgs.i));
        await page.emulateMedia({media: 'screen'});
        await page.pdf({
            path:path.normalize(avgs.o),
            printBackground:true,
            landscape:avgs.c,
            format:avgs.f,
            margin:{
                top:"10mm",
                left:"10mm",
                right:"10mm",
                bottom:"10mm"
            }
        });
        await browser.close();
    }
    catch(e){
        console.log(e);
        if(browser){
            await browser.close();
        }
    }
})();

